/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import { h, resolveComponent } from 'vue'
import modelHeader from './warehouse/ProductModelBody.vue'
import gridFooter from './warehouse/Ware_OutWareHouseGridFooter'
import { chunkArray, getDatakey } from '@/uitils/utils'
let extension = {
  data() {
    return {
      unitList: [],
      outStoreTypeList: [],
    }
  },
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: gridFooter,
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: {
      emits: ['parentCall'],
      render() {
        return [
          h(
            resolveComponent('el-alert'),
            {
              style: { 'margin-bottom': '5px' },
              'show-icon': true,
              type: 'success',
              closable: false,
              title: '直接点击【出库数量】可以直接进行修改',
            },
            ''
          ),
        ]
      },
    },
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      this.single = true
      this.columnIndex = true
      //点击单元格编辑与结束编辑(默认是点击单元格编辑，鼠标离开结束编辑)
      this.detailOptions.clickEdit = true
      this.tableMaxHeight = (document.body.clientHeight - 260) / 2

      this.columns.forEach((item) => {
        if (item.title == '操作') item.hidden = true
      })

      this.$nextTick(() => {
        getDatakey(['unitList', 'outStoreType']).then((res) => {
          // console.log(res);
          this.unitList = res[0].data
          this.outStoreTypeList = res[1].data
        })
      })

      let { permission } = this.$store.getters.getPermission(
        '/Ware_OutWareHouseBill'
      )
      if (permission.includes('print')) {
        this.buttons.push({
          name: '打 印',
          icon: 'el-icon-printer',
          type: 'warning',
          onClick: () => {
            let selectList = this.$refs.table.getSelected()
            if (selectList.length == 0)
              return this.$message.error('请选择要打印的单据')
            let rows = this.$refs.gridFooter.rows
            rows = rows.map((item) => {
              let unit = ''
              this.unitList.some((i) => {
                if (i.key == item.Unit_Id) {
                  unit = i.value
                  return true
                }
              })
              return {
                ...item,
                Unit_Id: unit,
              }
            })

            selectList = selectList.map((item) => {
              let outStoreType = ''
              this.outStoreTypeList.some((d) => {
                if (d.key == item.OutWareHouseBillType) {
                  outStoreType = d.value
                  return true
                }
              })

              return {
                ...item,
                OutWareHouseBillType: outStoreType,
              }
            })

            let data = {
              mainData: selectList[0],
              detailData: rows,
            }
            console.log(data)
            this.print(data)
          },
        })
      }
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      this.detailOptions.buttons.forEach((item) => {
        item.hidden = item.name == '添加行' ? true : false
      })
      this.detailOptions.buttons.unshift({
        name: '选择产品', //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        hidden: false, //是否隐藏按钮(如果想要隐藏按钮，在onInited方法中遍历buttons，设置hidden=true)
        onClick: function () {
          //触发事件
          // console.log(this.editFormFields);
          let type = ''
          if (this.editFormFields.OutWareHouseBillType == 'outsource')
            type = 'outsource'
          this.$refs.modelHeader.open(type)
        },
      })

      this.detailOptions.columns.forEach((item) => {
        if (
          item.field == 'MaxInventory' ||
          item.field == 'MinInventory' ||
          item.field == 'SafeInventory' ||
          item.field == 'InventoryQty'
        ) {
          item.hidden = true
        }
      })
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      if (result.length > 0) {
        this.$nextTick(() => {
          this.$refs.gridFooter.rowClick(result[0], 'wareHouse')
        })
      }

      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row) //单击行时选中当前行;
      //调用Doc_Order1GridFooter.vue文件中(订单明细)的查询
      this.$refs.gridFooter.rowClick(row)
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      this.editFormOptions.forEach((item) => {
        item.forEach((x) => {
          //如果是编辑设置为只读
          if (x.field == 'OutWareHouseBillCode') {
            //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
            //vue3版本改为设置：x.disabled=isEDIT
            x.placeholder = '请输入，忽略将自动生成'
          }
        })
      })

      this.boxButtons.forEach((item) => {
        if (item.value == 'save') {
          if (this.currentAction == 'update') item.hidden = true
          else item.hidden = false
        }
      })

      this.$refs.detail.changeTotal(0)
    },
    print({ mainData, detailData }) {
      console.log(mainData)
      console.log(detailData)
      let printWindow = window.open('', '_blank')
      let {
        OutWareHouseBillCode,
        OutWareHouseBillType,
        OutWareHouseDate,
        Creator,
      } = mainData
      printWindow.document.open()
      let style = `<style>
                      .title {
                        text-align:center;
                        position: relative;
                        margin: 5px 0;
                      }

                      .header {
                        display: flex;
                        font-size: 14px;
                      }

                      .t_head {
                        flex: 1;
                        display: flex;
                      }

                      .t_head .th_item {
                        display: flex; 
                        list-style: none;
                        flex-direction: column;
                        flex: 1;
                      }

                      .t_head .th_item .th_title {
                        flex: 1; 
                        display: flex; 
                        justify-content: center;
                      }

                      .th_title .th_title_space {
                        display: flex; 
                        flex: 1;
                        flex-direction: column;
                        justify-content: flex-end;
                      }

                      .label {
                        display: flex;
                        align-items: flex-end;
                        text-align: left;
                      }

                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                        font-size: 12px;
                      }

                      .grid_table tr,.grid_table tr td{
                        border: 1px dotted black;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: space-between; 
                        list-style: none;
                        font-size: 12px;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 150px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }

                      .cb {
                        margin-left: 20px;
                        text-align: left;
                      }
                    </style>`
      let title = `<div>
                        <h2 class="title">昆山鸿永峻精密五金电子科技有限公司</h2>
                        <h3 class="title">出库单</h3>
                    </div>`

      let header = `<div class="header">
                        <div class="t_head">
                          <ul class="th_item">
                            <li class="th_title">
                              <span class="label"> 出库单号: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${OutWareHouseBillCode}</span>
                            </li>
                            <li class="th_title">
                              <span class="label"> 出库类型: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${OutWareHouseBillType}</span>
                            </li>
                            
                          </ul>

                          <ul class="th_item">
                            <li class="th_title">
                              <span class="label"> 出库时间: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${OutWareHouseDate}</span>
                            </li>
                            <li class="th_title">
                              <span class="label"> 创&nbsp;&nbsp;建&nbsp;&nbsp;人: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${Creator}</span>
                            </li>
                          </ul>
                        </div>
                    </div>`
      let footer = `<div>
                    <ul class="footer"> 
                      <li>
                        核准
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        品质部
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        送货人
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        客户回签
                        <span class="footer_space"></span>
                      </li>
                    </ul>
                  <div>`
      let table = ''
      let result = chunkArray(detailData, 24)
      console.log(result)
      result.forEach((arr) => {
        let main = ``
        arr.forEach((item, index) => {
          main += `<tr>
            <td>${index + 1}</td>
            <td>${item.ProductName}</td>
            <td>${item.ProductCode}</td>
            <td>${item.ProductStandard == null ? '' : item.ProductStandard}</td>
            <td>${item.Unit_Id}</td>
            <td>${item.Type}</td>
            <td>${item.OutStoreQty}</td>
            <td></td>
          </tr>`
        })

        table += `
        <table class="grid_table">
          <thead>
            <tr>
              <th style="width: 50px;">序号</th>
              <th>物料名称</th>
              <th>物料编码</th>
              <th>规格</th>
              <th>单位</th>
              <th>类别</th>
              <th>出库数量</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            ${main}
          </tbody>
        </table>${footer}`
      })

      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(title)
      printWindow.document.write(header)
      printWindow.document.write(table)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
